<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2016/11/18
 * Time: 10:11
 */

namespace App\Plugins\Shh\Services;

use App\Models\Customer;
use App\Models\Group;
use App\Models\Project;
use App\Services\Repo\CustomerRepo;
use Illuminate\Database\Eloquent\Model;
use \Auth;

class CustomerService extends CustomerRepo
{

    public function find(array $_filter):Model
    {
        $user = Auth::User();
        $customer = parent::find($_filter);
        // 把houseInfo的id转为string
        if (!empty($customer['houseInfo'])) {
            // 如果是叶子节点的账号, 当前账号只能看到自己所在结构中的客户房屋信息
            $projects = Project::where('users', $user->id)
                ->get()->pluck('_id')->all();
            // 上级账号, 返回房屋信息处理
            if (empty($projects)) {
                // 获取上级账号所有的项目id
                $group_id = $user->group_id;
                $group = new Group();
                $groups = $group->getLeafBy($group_id);
                $group_ids = [];
                foreach ($groups as $v) {
                    array_push($group_ids, $v->id);
                }
                $shhKey = Project::whereIn('group_id', $group_ids)->get()->pluck('plugins.shihui.key')->all();
            } else {
                // 下级账号
                $project_id = $projects[0];
                $project = Project::find($project_id);
                $shhKey = $project->plugins['shihui']['key'];
                $shhKey = array($shhKey);
            }
            $houseInfo = [];
            foreach ($customer['houseInfo'] as $k=>$v) {
                // 粗略的判断houseInfo字段的格式
                if (!is_array($v)) {
                    continue;
                }
                if ($k === 'address') {
                    continue;
                }
                if (in_array($v['shhKey'], $shhKey)) {
                    array_push($houseInfo, $v);
                }
            }
            $customer->houseInfo = $houseInfo;
        }
        return $customer;
    }
}